<?php require_once 'httpFilter.php'; 'conf.php'; ?>
<?php
$budgetName = $_REQUEST["budgetName"];
$templateType = $_REQUEST["templateType"];
$budgetIdToCopy = $_REQUEST["budgetIdToCopy"];

$errCode = 0;
$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
if (!$con) {
	die('Could not connect: ' . mysql_error());
}

mysql_select_db(GlobalConfig::db_name, $con);

$query = "select * from budget where month = '" . $budgetName . "' and userid=". $_SESSION["userid"];
error_log($query);
$result = mysql_query($query);
if (!$result) {
	$errCode = 1;
}

$count = 0;
while ($row = mysql_fetch_array($result)) {
	$count++;
}

//database name already exists
if ($count != 0) {
	$errCode = 2;
} else {

	//We create the budget
	$query = "insert into budget (userid, month, created, carryover) values ('". $_SESSION["userid"] . "','" . $budgetName . "', NOW(), 0)";
	error_log($query);
	$result = mysql_query($query);
	if (!$result) {
		$errCode = 1;
	}

	//Get the budget id
	$result = mysql_query("select max(id) id from budget");
	if (!$result) {
		$errCode = 1;
	} else {
		while ($row = mysql_fetch_array($result)) {
			$newBudgetId = $row['id'];
		}
	}

	//We copy the budget items from the template
	if ($templateType == "inbuiltTemplate") {
		$result = mysql_query("select * from budgetitem where budgetid = 1");
		if (!$result) {
			$errCode = 1;
		} else {
			while ($row = mysql_fetch_array($result)) {
				$result1 = mysql_query("insert into budgetitem (budgetId, categoryId, expense, description, budgetAmount, actualAmount) values (" . $newBudgetId . ", " . $row['categoryId'] . ", " . $row['expense'] . ", '" . $row['description'] . "', " . $row['budgetAmount'] . ", 0)");
				if (!$result1) {
					$errCode = 1;
				}
			}
		}
	} else	if ($templateType == "existingBudget") {
			$query  = "select * from budget_budgetitem where budgetid=". $budgetIdToCopy;
			error_log($query);
			$result = mysql_query($query);
			if (!$result) {
				$errCode = 1;
			} else {
				while ($row = mysql_fetch_array($result)) {
					$query  = "insert into budget_budgetitem (budgetid, budgetitemid, budgetAmount, actualAmount) values (". $newBudgetId .", ". $row["budgetitemid"] .", ". $row['budgetAmount'] .", 0)";
					error_log($query);
					$result1 = mysql_query($query);
					if (!$result1) {
						$errCode = 1;
					}
				}
			}


		}
}
mysql_close($con);
?>
<result>
	<code>
		<?=$errCode?>
	</code>
	<newBudgetId>
		<?=$newBudgetId?>
	</newBudgetId>
</result>